<template>
  <el-dialog
    title="新建目录"
    :visible="dialogVisible"
    close-on-press-escape
    :close-on-click-modal="false"
    custom-class="custom-dialog"
    @opened="inputFocus"
    @close="closeDialog"
    width="26rem"
  >
    <el-form ref="form" :model="form" :rules="rules">
      <el-form-item prop="title">
        <el-input
          ref="input"
          v-model="form.title"
          placeholder="请输入目录名"
          @keyup.enter.native="onSubmit"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" class="flex content-space-between">
      <el-button
        type="primary"
        @click="onSubmit"
        :loading="loading"
        v-text="'创建目录'"
      />
      <el-button @click="closeDialog">取消</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { mapState } from 'vuex';

export default {
  name: 'create-folder-dialog', // 新建目录
  props: {
    dialogVisible: Boolean,
  },
  data() {
    return {
      form: { title: '' },
      rules: {
        title: [{ validator: this.$va.folderTitle, trigger: 'change' }],
      },
      loading: false,
    };
  },
  computed: {
    ...mapState({ curSpace: 'currentSpace' }),
    curFolderId() { return this.$route.params.folderId; },
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate().then(() => {
        this.loading = true;
        this.$api.spaceResources.createFolder({
          spaceId: this.curSpace.id,
          parentId: this.curFolderId,
          title: this.form.title.trim(),
        }).then((res) => {
          this.$message.success('创建成功');
          this.closeDialog();
          this.$refs.form.resetFields();
          this.$router.push(`/spaces/${this.curSpace.id}/resources/${res.data.id}`);
        }).catch(() => {})
          .then(() => { this.loading = false; });
      }).catch(() => {});
    },
    inputFocus() { this.$refs.input.focus(); },
    closeDialog() {
      this.$refs.form.resetFields();
      this.$emit('update:dialogVisible', false);
    },
  },
};
</script>

<style></style>
